package com.example.commonexport.service.impl;

import com.example.commonexport.entity.ExportResult;
import com.example.commonexport.service.ExportService;
import com.example.commonexport.service.ExportTask;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

// CSV导出服务实现
public class CsvExportServiceImpl implements ExportService {
    private final String exportDir;

    public CsvExportServiceImpl(String exportDir) {
        this.exportDir = exportDir;
        // 确保导出目录存在
        File dir = new File(exportDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    @Override
    public ExportResult exportData(ExportTask task) throws Exception {
        System.out.println("开始导出CSV数据: " + task.getTaskId());
        
        // 模拟从数据库或其他数据源获取数据
        List<Map<String, Object>> data = fetchExportData(task);
        
        // 构建导出文件路径
        String fileName = "export_" + task.getTaskId() + ".csv";
        File exportFile = new File(exportDir, fileName);
        
        try (FileWriter writer = new FileWriter(exportFile)) {
            // 写入CSV头部
            if (!data.isEmpty()) {
                Map<String, Object> firstRow = data.get(0);
                writer.append(String.join(",", firstRow.keySet()));
                writer.append("\n");
                
                // 写入数据行
                for (Map<String, Object> row : data) {
                    for (String key : firstRow.keySet()) {
                        Object value = row.get(key);
                        writer.append(value != null ? value.toString() : "");
                        writer.append(",");
                    }
                    writer.append("\n");
                }
            }
            
            System.out.println("CSV导出完成: " + exportFile.getAbsolutePath());
            return new ExportResult(true, exportFile.getAbsolutePath(), null);
        } catch (IOException e) {
            System.err.println("CSV导出失败: " + e.getMessage());
            throw e;
        }
    }
    
    // 模拟获取导出数据
    private List<Map<String, Object>> fetchExportData(ExportTask task) {
        // 实际实现中，这里会从数据库或其他数据源获取数据
        // 为演示目的，返回空列表
        return List.of();
    }
}    